package main

//带参数的定时任务包
import (
	"fmt"
	"github.com/jakecoffman/cron"
	"strconv"
)

type SchduleActiveCallback func(*Task)

type ScheduleJob struct {
	info *Task
	callback SchduleActiveCallback
}

func NewScheduleJob(_id *Task, _job SchduleActiveCallback) *ScheduleJob {
	instance := &ScheduleJob{
		info:       _id,
		callback: _job,
	}
	return instance
}

func (this *ScheduleJob) Run() {
	if nil != this.callback {
		this.callback(this.info)
	} else {
		fmt.Println("Invalid callback function")
		return
	}
}

type ScheduleManager struct {
	cronJob *cron.Cron
}

func NewScheduleManager() *ScheduleManager {
	instance := &ScheduleManager{}
	instance.cronJob = cron.New()
	return instance
}

//启动
func (this *ScheduleManager) Start() {
	this.cronJob.Start()
}

func (this *ScheduleManager) Stop() {
	this.cronJob.Stop()
}

/**
添加任务
*/
func (this *ScheduleManager) AddJob(info *Task, scheduleActive func(*Task)) {
	job := NewScheduleJob(info, scheduleActive)
	//job := NewScheduleJob(id, scheduleActive)
	this.cronJob.AddJob(info.Cron, job, strconv.Itoa(info.Id))
}

//移除任务
func (this *ScheduleManager) RemoveJob(name string) {
	this.cronJob.RemoveJob(name)
}

//获取所有的任务
func (this *ScheduleManager) Entries() []*cron.Entry {
	return this.cronJob.Entries()
}

func (this *ScheduleManager) Pos(name string) int {
	for p, e := range this.cronJob.Entries() {
		if e.Name == name {
			return p
		}
	}
	return -1
}
